package com.example.dishfo.myapplication.activity.userlogin;

import android.annotation.SuppressLint;
import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.DefaultLifecycleObserver;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.OnLifecycleEvent;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;

import com.example.dishfo.myapplication.context.HoldApplication;
import com.example.dishfo.myapplication.context.casual.ComponentManager;
import com.example.dishfo.myapplication.entity.User;
import com.example.dishfo.myapplication.network.netintr.UserService;
import com.example.dishfo.myapplication.network.resbean.HttpBean;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * this class should be read in main thread
 * 一个和activity耦合度较高的 viewmodel
 *  登陆界面的逻辑在这里完成
 */

public class UserViewModel extends AndroidViewModel
        implements UserAction,LifecycleObserver{

    private MutableLiveData<User> currentUser;
    private MutableLiveData<HttpBean> signUpRes;
    private MutableLiveData<User> savedUser;
    private boolean isLogining=false;
    private boolean isSigUp=false;

    @Inject
    UserService service;

    public UserViewModel(@NonNull Application application) {
        super(application);
        savedUser=new MutableLiveData<>();
        if(application instanceof ComponentManager){
            ((ComponentManager) application).getServiceComponent().inject(this);
        }else {
            throw new RuntimeException("you should check your code");
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStart(){
        savedUser.setValue(((HoldApplication)getApplication()).getSavedUser());
    }

    public LiveData<User> getCurrentUser(){
        if(currentUser==null){
            currentUser=new MutableLiveData<>();
        }
        return currentUser;
    }

    public LiveData<User> getSavUser(){
        return savedUser;
    }

    /**
     *
     * @param user username to login
     * @param pwd pwd to login
     */
    @MainThread
    @SuppressLint("CheckResult")
    @Override
    public void onLogin(String user, String pwd) {

        if(isLogining){
            return;
        }
        Observable<HttpBean> ob=service.login(user,pwd);
        isLogining=true;
        ob.observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(httpBean -> {
                    if(!isLogining){
                        return;
                    }
                    if(httpBean.getCode()==1){
                        Gson gson=new Gson();
                        Application application=getApplication();
                        JsonObject object=gson.fromJson(httpBean.getForm(),JsonObject.class);
                        User var1=gson.fromJson(object.get("user").getAsString(),User.class);
                        var1.setPassword(pwd);
                        String token=object.get("token").getAsString();
                        if(application instanceof HoldApplication){
                            ((HoldApplication) application).loginCompete(var1,token);
                        }
                        currentUser.setValue(var1);
                    }else {
                        currentUser.setValue(null);
                    }
                    isLogining=false;
                });
    }

    /**
     * 当用户取消登陆时调用
     */
    @MainThread
    @Override
    public void cancelLogin() {
        if(isLogining){
            isLogining=false;
        }
    }

    /**
     * emmmmmmmmmmmmm
     * @param name
     * @param pwd
     * @param email
     */
    @SuppressLint("CheckResult")
    @Override
    public void signUp(String name, String pwd, String email) {
        if(isSigUp){
            return;
        }
        isSigUp=true;
        Observable<HttpBean> observable=service.toSignUp(email,name,pwd);
        observable.observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(httpBean -> {
                    if(!isSigUp){
                        return;
                    }
                    isSigUp=false;
                    signUpRes.setValue(httpBean);
                },throwable -> {
                    if(!isSigUp){
                        return;
                    }
                    isSigUp=false;
                    HttpBean bean=new HttpBean();
                    bean.setCode(-1);
                    bean.setMsg("");
                    signUpRes.setValue(bean);
                });
    }

    @MainThread
    @Override
    public void cancelSignUp() {
        if(isSigUp){
            isSigUp=false;
        }
    }

    @Override
    public LiveData<HttpBean> getSignUpRes() {
        if(signUpRes==null){
            signUpRes=new MutableLiveData<>();
        }
        return signUpRes;
    }



}
